package com.bxl.netty.rpc.register.server;

import com.bxl.netty.rpc.common.builder.MsgBuilder;
import com.bxl.netty.rpc.common.context.Context;
import com.bxl.netty.rpc.common.message.RegisterContent;
import com.bxl.netty.rpc.common.serialize.Serialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * <>
 *
 * @author baixl
 * @date 2021/2/23
 */
public class RegisterServerMsgDecoder extends ByteToMessageDecoder {
    private final static int HEADER_LENGTH = 16;// header的长度
    private Context context;
    private Serialize serialize;

    public RegisterServerMsgDecoder() {
    }

    public RegisterServerMsgDecoder(Context context) {
        assert context == null;
        this.context = context;
        this.serialize = context.getSerialize();
    }
    
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 长度不足，退出
        if (in.readableBytes() < HEADER_LENGTH) {
            return;
        }
        // 获取协议的版本
        int flag = in.readInt();
        // 获取消息长度
        long requestID = in.readLong();
        //消息体长度
        int length = in.readInt();
        
        if(length > 0){
            if (in.readableBytes() < length) {
                in.setIndex(in.readerIndex() - HEADER_LENGTH, in.writerIndex());
                return;
            }
            // 获取SessionId
            byte[] content = new byte[length];
            in.readBytes(content);
            out.add(MsgBuilder.createMsg(flag, requestID, (RegisterContent) serialize.deserialize(content))); 
        }else{
            out.add(MsgBuilder.createMsg(flag, requestID, new RegisterContent()));
        }
        
        
    }
}
